package jackson;

import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.TypeFactory;

import java.io.IOException;
import java.io.Serializable;
import java.util.List;

/**
 * .
 *
 * @author sunhao(sunhao.java@gmail.com)
 * @version V1.0, 16/1/18 下午12:49
 */
public class TestJacksonGenerics {
    private static final ObjectMapper jsonObjectMapper = new ObjectMapper();

    public static void main(String[] args) throws IOException {
        JavaType mainClazz = makeJavaType(List.class);
        JavaType genericClazz = makeJavaType(Demo.class);

//        JavaType mainClazzContainsGeneric = CollectionType.construct(mainClazz.getRawClass(), genericClazz);
//        TypeReference<List<Demo>> typeReference = new TypeReference<List<Demo>>() {
//        };
//        JavaType mainClazzContainsGeneric = mainClazz.withContentType(genericClazz);

        JavaType mainClazzContainsGeneric = new ObjectMapper().getTypeFactory().constructParametricType(List.class, Demo.class);

        List<Demo> demos = jsonObjectMapper.readValue("[{\"pkId\":1,\"name\":\"sunhao\"},{\"pkId\":2,\"name\":\"sunhao\"}]", mainClazzContainsGeneric);
        System.out.println(demos);
        System.out.println(demos.get(0).getName());
    }

    public static JavaType makeJavaType(Class<?> clazz) {
        return TypeFactory.defaultInstance().constructType(clazz);
    }

    static class Demo implements Serializable {
        private Long pkId;

        private String name;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public Long getPkId() {
            return pkId;
        }

        public void setPkId(Long pkId) {
            this.pkId = pkId;
        }

        @Override
        public String toString() {
            return "Demo{" +
                    "pkId=" + pkId +
                    ", name='" + name + '\'' +
                    '}';
        }
    }
}
